package vben.core.module.sys.org.role;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Service;
import vben.core.common.mvc.service.BaseMainService;
import vben.core.module.sys.org.root.SysOrg;
import vben.core.module.sys.org.root.SysOrgRepo;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class SysOrgRoleTreeService extends BaseMainService<SysOrgRoleTree> {

    public String insertx(SysOrgRoleTree main) {
        String id = insert(main);
        List<SysOrg> list = new ArrayList<>();
        for (SysOrgRole role : main.getRoles()) {
            SysOrg sysOrg = new SysOrg(role.getId(), role.getName(), 32);
            list.add(sysOrg);
        }
        orgRepo.saveAll(list);
        return id;
    }

    public String updatex(SysOrgRoleTree main) {
        String id = update(main);
        List<SysOrg> list = new ArrayList<>();
        for (SysOrgRole role : main.getRoles()) {
            SysOrg sysOrg = new SysOrg(role.getId(), role.getName(), 32);
            list.add(sysOrg);
        }
        orgRepo.saveAll(list);
        return id;
    }

    public SysOrg calc(String useid, String rolid) {
        String sql = "select t.tier \"tier\",m.ornum \"ornum\" from sys_org_role_node t " +
                "inner join sys_org_role m on m.treid=t.treid where t.memid=? and m.id=?";
        Map<String, Object> map = jdbcDao.findMap(sql, useid, rolid);
        if (map == null) {
            sql = "select t.tier \"tier\",m.ornum \"ornum\" from sys_org_role_node t " +
                    "inner join sys_org_role m on m.treid=t.treid " +
                    "inner join sys_org_user u on u.depid=t.memid where u.id=? and m.id=?";
            map = jdbcDao.findMap(sql, useid, rolid);
            if (map == null) {
                return null;
            }
        }
        String tier = (String) map.get("tier");
        Integer ornum =(Integer) map.get("ornum");
        String[] idArr = tier.split("x");
        String sql3 = "select o.id,o.name,o.type from sys_org_role_node t inner join sys_org o on o.id=t.memid where t.id=?";
        SysOrg org = jdbcDao.getTp().queryForObject(sql3,
                new Object[]{idArr[ornum]}, new BeanPropertyRowMapper<>(SysOrg.class));
        return org;
    }

    @Autowired
    private SysOrgRepo orgRepo;

    @Autowired
    private SysOrgRoleTreeRepo repo;

    @PostConstruct
    public void initDao() {
        super.setRepo(repo);
    }

}

